<?php
/**
 * Created by PhpStorm.
 * User: C。
 * Date: 2019/8/13
 * Time: 9:04
 */
namespace app\home\controller;

use app\common\model\Member as MemberModel;
use app\common\model\ZhMemberLog as ZhMemberLogModel;
use app\common\model\MemberLoginIp as MemberLoginIpModel;
use app\common\model\Mzongpai as MzongpaiModel;
use app\common\model\MemberQuan as MemberQuanModel;
use app\common\model\Ilike as IlikeModel;
use app\common\model\Friends as FriendsModel;
use app\common\model\Manager as ManagerModel;
use app\common\model\Renzhen as Renzhenmodel;
use app\common\model\Config as Configmodel;
use app\common\model\Wechat as WechatModel;
use app\common\model\Weibo as WeiboModel;
use app\common\model\Qq as QqModel;
use app\common\model\NewsCommentMessage as NewsCommentMessageModel;
use app\common\model\MemberQuality as MemberQualityModel;
use think\Db;
/**
 * Member 个人中心
 * Class Member
 * @package app\home\controller
 */
class Member extends Base
{
    /**
     * [getIndex  获取个人中心数据]
     * @param
     * @return json
     * @author [C。]
     */
    public function getIndex()
    {
        $param = input('param.');
        $mem = $this->getMember($param['token']);
        $model = new MemberModel();
        $zmodel = new MzongpaiModel();
        $qmodel = new MemberQuanModel();
        $imodel = new IlikeModel();
        $fmodel = new FriendsModel();
        $mmodel = new ManagerModel();
        $wmodel = new WechatModel();
        $rmodel = new Renzhenmodel();
        $wemodel = new WeiboModel();
        $qqmodel = new QqModel;
        $nmodel = new NewsCommentMessageModel();
//        $tmodel = new TopicMessageModel();
        $ipmodel = new MemberLoginIpModel;
        $mqmodel = new MemberQualityModel;
        $cmodel = new ConfigModel;
        $map = [];
        $map1 = [];
        $map2 = [];
        $map3 = [];
        try{
            $ip = getIP();
            $address = getipaddress($ip);
            $address = json_decode($address,true); //数据转换
            if(!empty($mem['tel'])){
                $type = getphonetype($mem['tel']);
            }else{
                $type = 4;
            }

            $ipaddr = $ipmodel->findData($mem['id'],'mid');

            if(empty($ipaddr) && !empty($address['content'])){
                $ipmodel->addData(['mid'=>$mem['id'],'ip'=>$ip,'province'=>$address['content']['address_detail']['province'],'city'=>$address['content']['address_detail']['city'],'operator'=>$type]);
            }else{
                $ipmodel->editData(['id'=>$ipaddr['id'],'ip'=>$ip,'province'=>$address['content']['address_detail']['province'],'city'=>$address['content']['address_detail']['city'],'operator'=>$type]);
            }

            $today_quality = $mqmodel->getSum(['mid'=>$mem['id'],'create_time'=>['between',[strtotime(date('Y-m-d')),strtotime(date('Y-m-d')) + 24*3600]]],'quality');
            $mem['today_quality'] = $today_quality;

            $quality_leavel = $cmodel->findData('quality_leavel','cname','cvalue');
            if(empty($quality_leavel['cvalue'])){
                $mem['quality_leavel'] = config('quality.quality_leavel');
            }else{
                $mem['quality_leavel'] = unserialize($quality_leavel['cvalue']);
            }
            foreach($mem['quality_leavel'] as $k=>$v){
                if($mem['quality'] >= $v['quality'] && $mem['quality'] < $mem['quality_leavel'][$k+1]['quality']){
                    $mem['level'] = $v['name'];
                    $mem['level_num'] = $v['level'];
                }
            }

            $newmessage = $nmodel->findOne(['mid'=>$mem['id'],'is_read'=>1]);
//            $topicmessage = $tmodel->findOne(['mid'=>$mem['id'],'is_read'=>1]);
            if(!empty($newmessage)){
                $mem['is_read'] = 1;
            }else{
                $mem['is_read'] = 2;
            }
            if(!empty($mem['zid'])){
                $zongpzi = $zmodel->findData($mem['zid']);
                $mem['zongpai'] = $zongpzi['name'];
            }else{
                $mem['zongpai'] = '';
            }
            $mem['addtime'] = date('Y-m-d H:i:s',$mem['addtime']);
            $mem['conversiontime'] = date('Y-m-d',$mem['conversiontime']);
            $map1['member_id'] = $mem['id'];
            $quan = $qmodel->getNum($map1);
            $mem['quan'] = $quan;

            $map['i.memid'] = $mem['id'];
            $map['i.status'] = 1;
            $mem['guanzhu'] = $imodel->getCount($map);

            $map2['unino'] = ['like','%\_'.$mem['id'].'\_%'];
            $map2['states'] = 1;
            $mem['friends'] = $fmodel->getCountByCondition($map2);

            $wechat = $wmodel->findData($mem['id'],'memid');
            if(empty($wechat)){
                $mem['is_wechat'] = 0;
            }else{
                $mem['is_wechat'] = 1;
            }
            $weibo = $wemodel->findData($mem['id'],'mid');
            if(empty($weibo)){
                $mem['is_weibo'] = 0;
            }else{
                $mem['is_weibo'] = 1;
            }
            $qq = $qqmodel->findData($mem['id'],'mid');
            if(empty($qq)){
                $mem['is_qq'] = 0;
            }else{
                $mem['is_qq'] = 1;
            }
            if(empty($mem['img'])){
                $mem['img'] = 'https://fushan.oss-cn-hangzhou.aliyuncs.com/nouser.png';
            }else{
                $http = substr($mem['img'],0,4);
                if($http != 'http') {
                    $mem['img'] = config('domain_name') . $mem['img'];
                }
            }

            $renzhen = $rmodel->findData($mem['id'],'uid');
            if(empty($renzhen)){
                $mem['isrenzhen'] = 2;
            }else{
                $mem['isrenzhen'] = $renzhen['status'];
            }

            $map3['tel'] = $mem['tel'];
            $map3['states'] = ['neq',3];
            $manager = $mmodel->findOne($map3,'*');
            if(!empty($manager)){
                $mem['identity'] = 2;
                $mem['fahao'] = $manager['username'];
                if($mem['identity'] == 1){
                    $model->editData(['id'=>$mem['id'],'identity'=>2]);
                }
                $mem['isrenzhen'] = 1;
            }else{
                $mem['identity'] = 1;
                if($mem['identity'] == 2){
                    $model->editData(['id'=>$mem['id'],'identity'=>1]);
                }
                if(empty($renzhen)){
                    $mem['isrenzhen'] = 3;
                }elseif ($mem['isrenzhen'] == 1){
                    $mem['isrenzhen'] = 3;
                }
            }


            $config = get_config();
            $mem['contactus'] = $config['contactus'];
            if(empty($mem['bjimg'])){
                $mem['bjimg'] = config('home.bj_img');
            }
            if(empty($mem['introduction']) && $mem['introduction'] !== 0){
                $mem['introduction'] = '';
            }
            if(empty($mem['city']) && $mem['city'] !== 0){
                $mem['city'] = '';
            }
            if(empty($mem['bathday']) && $mem['bathday'] !== 0){
                $mem['bathday'] = '';
            }
            if(empty($mem['zongpai']) && $mem['zongpai'] !== 0){
                $mem['zongpai'] = '';
            }
            if(empty($mem['conversiontime']) && $mem['conversiontime'] !== 0){
                $mem['conversiontime'] = '';
            }

        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$mem);
    }
    /**
     * [postHeader  换头像]
     * @param   type 1换头像 2换背景
     * @return json
     * @author [C。]
     */
    public function postHeader()
    {
        $param = input('param.');
        $qmodel = new MemberQualityModel();
        try{
            $mem = $this->getMember($param['token']);
            $pic = $param['img'];
            $model = new MemberModel;
            if($param['type'] == 1){
                $data = array(
                    'id'=>$mem['id'],
                    'img'=>$pic
                );
            }elseif ($param['type'] == 2){
                $data = array(
                    'id'=>$mem['id'],
                    'bjimg'=>$pic
                );
            }

            $model->editData($data);
            $quality = $qmodel->findOne(['mid'=>$mem['id'],'type'=>37]);
            if(empty($quality)){
                add_quality($mem['id'],37,$mem['quality'],5);
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '修改失败'.$e->getMessage());
        }
        return admin_json(1, '修改成功');
    }
    /**
     * [postEdit  编辑信息]
     * @param
     * @return json
     * @author [C。]
     */
    public function postEdit()
    {
        $param = input('param.');
        $model = new MemberModel();
        $qmodel = new MemberQualityModel();
//        $mmodel = new ManagerModel();
//        $rmodel = new RenzhenModel();
//        $wmodel = new Wechat();
        $mem = $this->user;
        try{
//            if($param['identity'] == 1){
//                $data = array(
//                    'id'=>$mem['id'],
//                    'img' => $param['img'],
//                    'username' => $param['username'],
//                    'introduction' => $param['introduction'],
//                    'city'=>$param['city'],
//                    'bathday' => $param['bathday'],
//                    'zid' => $param['zid'],
//                    'identity' => $param['identity'],
//                    'sex' => $param['sex'],
//                );
            $param['id'] = $mem['id'];
            if(!empty($param['conversiontime'])){
                $param['conversiontime'] = strtotime($param['conversiontime']);
            }
//            if(!empty($param['states'])){
//                if($param['states'] == 3){
//                    $param['tel'] = '';
//                    $param['token'] = '';
//                    $wechat = $wmodel->findData($mem['id'],'memid','id');
//                    if(!empty($wechat)){
//                        $wmodel->editData(['id'=>$wechat['id'],'memid'=>0]);
//                    }
//                }
//            }
//            if(!empty($param['city'])){
//                $param['city'] = join(',',$param['city']);
//            }
            $model->editData($param);
            $quality = $qmodel->findOne(['mid'=>$mem['id'],'type'=>33]);
            if(empty($quality)){
                add_quality($mem['id'],33,$mem['quality'],5);
                $add = 1;
            }
            $quality1 = $qmodel->findOne(['mid'=>$mem['id'],'type'=>38]);
            if(empty($quality1)){
                if(empty($add)){
                    $quality_num = $mem['quality'];
                }else{
                    $quality_num = $mem['quality'] + 20;
                }
                add_quality($mem['id'],38,$quality_num,5);
            }
//            }elseif ($param['identity'] == 2){
//                $data = array(
//                    'id'=>$mem['id'],
//                    'img' => $param['img'],
//                    'username' => $param['username'],
//                    'introduction' => $param['introduction'],
//                    'sex' => $param['sex'],
//                    'province' => $param['province'],
//                    'city' => $param['city'],
//                    'qu' => $param['qu'],
//                    'bathday' => $param['bathday'],
//                    'zid' => $param['zid'],
//                    'identity' => $param['identity'],
//                );
//                $model->editData($data);
//
//
//                $img = $param['zcard'].','.$param['fcard'].','.$param['jiedie'];
//                $data1 = array(
//                    'type'=>1,
//                    'idcard'=>$param['idcard'],
//                    'fahao'=>$param['fahao'],
//                    'siyuan'=>$param['siyuan'],
//                    'jiedie'=>$img,
//                    'addtime'=>time(),
//                    'uid'=>$mem['id']
//                );
//                if($mem['identity'] == 0){
//                    $mmodel->addData($data1);
//                }else{
//                    $mmodel->editData1($data1);
//                }
//            }


        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '修改失败'.$e->getMessage());
        }
        return admin_json(1, '修改成功');
    }
    /**
     * [postEditPass  修改密码]
     * @author [C。]
     * @return json
     */
    public function postEditPass()
    {
        $param = input('param.');
        $mem = $this->getMember($param['token']);
        $model = new MemberModel();
        $qmodel = new MemberQualityModel();
        try{
            if(empty($mem['pswd'])){
                $model->editData(['id'=>$mem['id'],'pswd'=>md5($param['npass'])]);
            }else{
                if($mem['pswd'] != md5($param['upass'])){
                    return admin_json(-2, '原密码错误！');
                }
                $model->editData(['id'=>$mem['id'],'pswd'=>md5($param['npass'])]);
            }
            $quality = $qmodel->findOne(['mid'=>$mem['id'],'type'=>39]);
            if(empty($quality)){
                add_quality($mem['id'],39,$mem['quality'],5);
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '修改失败'.$e->getMessage());
        }
        return admin_json(1, '修改成功');
    }
    /**
     * [getLoginRecord  添加登录记录]
     * @author [C。]
     * @return json
     */
    public function getLoginRecord()
    {
        $param = input('param.');
        $mem = $this->getMember($param['token']);
        //判断会话是否过期
        if (time() - $mem['tokentime'] > config('home.token_expire')) {
            $token = md5('app' . $mem['tel'] . config('home.token_halt').time());
            Db::name('member')->where('id',$mem['id'])->update(['token'=>$token,'tokentime'=>time()]);
        }else{
            $token = $mem['token'];
        }
        $day = strtotime(date('Y-m-d'));
        $sday = $day - 3600*24*7;
        if($mem['addtime'] < $sday){
//            $data = array('status' => 0,'msg' => '用户注册时间已经超过7天');
            return admin_json(1,'获取成功',['token'=>$token]);
        }

        $record = Db::name('login_record')->where(['memid' => $mem['id'],'logintime' => $day])->find();
        if(!empty($record)){
//            $data = array('status' => 0,'msg' => '该用户今天已登录');
            return admin_json(1,'获取成功',['token'=>$token]);
        }

        $result = Db::name('login_record')->insert(['memid' => $mem['id'],'logintime' => $day]);
        if(!empty($result)){
//            $data = array('status' => 1,'msg' => '添加成功');
            return admin_json(1,'获取成功',['token'=>$token]);
        }else{
//            $data = array('status' => 0,'msg' => '添加失败');
            return admin_json(1,'获取成功',['token'=>$token]);
        }
    }
    /**
     * [getInviteNum  获取邀请人数]
     * @author [C。]
     * @return json
     */
    public function getInviteNum()
    {
        $param = input('param.');
        $model = new MemberModel();
        $mem = $this->getMember($param['token']);
        try{
            $num = $model->getAllCount(['agent_id'=>$mem['id']]);
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        $data = array(
            'num'=>$num,
            'jifen'=>$mem['jifen']
        );
        return admin_json(1, '获取成功',$data);
    }
    /**
     * [getZongpai  获取宗派]
     * @author [C。]
     * @return json
     */
    public function getVerypass()
    {
        $param = input('param.');
        $user = $this->user;
        $pass = md5($param['pass']);
        if(empty($user['pswd'])){
            return admin_json(-1, '请设置密码');
        }
        if($pass == $user['pswd']){
            return admin_json(1, '验证成功');
        }else{
            return admin_json(-2, '密码错误');
        }
    }
    /**
     * [getZongpai  获取宗派]
     * @author [C。]
     * @return json
     */
    public function getZongpai()
    {
        $model = new MzongpaiModel();
        try{
            $data = $model->getAllData();
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$data);
    }
    /**
     * [getZongpai  获取邀请页内容]
     * @author [C。]
     * @return json
     */
    public function getInvite()
    {
        $param = input('param.');
        $model = new MemberModel();
        $mem = $this->getMember($param['token']);
        $map = [];
        try{
            $map['agent_id'] = $mem['id'];
            $count = $model->getAllCount($map);
            $data = array(
                'qrcode' => 'http://'.$_SERVER['HTTP_HOST'].'/'.$mem['qrcode'],
                'jifen' => $mem['jifen'],
                'invite_num' => $count
            );
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$data);
    }
    /**
     * [getIp  获取ip]
     * @author [C。]
     * @return json
     */
    public function getIp()
    {
        return admin_json(1, '获取成功',['ip'=>getIP()]);
    }
    /**
     * [getAboutus  获取关于我们]
     * @author [C。]
     * @return json
     */
    public function getAboutus()
    {
        $model = new ConfigModel;
        $config = $model->findData('aboutus','cname','content');
        return admin_json(1,'获取成功',$config['content']);
    }
    /**
     * [postZhuce  智慧寺院注册]
     * @author [C。]
     * @return json
     */
    public function zhuce()
    {
        $param = input('param.');
        try{
            $mem = Db::name('member')->where(['tel'=>$param['tel']])->find();
            if(!empty($mem)){
                return admin_json('-1','该手机号已经注册！');
            }
            $map = [];
            $map['tel'] = $param['tel'];
            $map['code'] = $param['code'];
            $result = Db::name('vercode')->where($map)->find();
            if(!empty($result)) {
                if ($result['status'] == 2) {
                    return admin_json('-3', '验证码已使用');
                }
                if (time() - $result['addtime'] > config('home.code_expiration_time')) {
                    return admin_json('-2', '验证码已过期');
                }
                Db::name('vercode')->where($map)->update(['status' => 2]);
            }else{
                return admin_json('-1','手机号或验证码错误');
            }
            if(!empty($param['tels'])){
                $agent = Db::name('member')->where('tel',$param['tels'])->find();
                if(!empty($agent)){
                    $this->editJifen($agent['id']);
                    Db::name('member')->where('token', $param['token'])->update(['agent_id'=>$agent['id']]);
                }
            }
            Db::name('member')->where('token', $param['token'])->update(['tel'=>$param['tel'],'pswd'=>md5($param['pswd'])]);
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '注册失败'.$e->getMessage());
        }
        return admin_json(1, '注册成功');
    }
    /**
     * [postForgetpswd 邀请成功修改福豆]
     * @param
     * @author [C。]
     * @return json
     */
    public function editJifen($uid)
    {
        $mem = Db::name('member')->where('id',$uid)->find();
        if(!empty($mem)){
            $jifen = $mem['jifen'] + config('home.invite_jifen');
            Db::name('mjifen')->insert(['jifen'=>config('home.invite_jifen'),'memid'=>$uid,'addtime'=>time()]);
            Db::name('member')->where('id',$uid)->update(['jifen'=>$jifen]);
        }
    }
    /**
     * [getIndex  信徒列表]
     * @param
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function index()
    {
        $param = input('param.');
        $map = [];
        $this->getPageAndSize($param);
        $model = new ZhMemberLogModel;
        $mmodel = new MemberModel;
        $zmodel = new MzongpaiModel;
        try{
            $map['comid'] = $param['comid'];
            $count = $model->getCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getlist($map, $this->from, $this->size,'id,mid');
            foreach($lists as &$v){
                $member = $mmodel->findData($v['mid'],'id','id,img,tel,username,sex,city,bathday,zid,addtime');
                if(!empty($member['zid'])){
                    $zongpai = $zmodel->findData($member['zid'],'id','name');
                    $v['zongpai'] = $zongpai['name'];
                }else{
                    $v['zongpai'] = '无';
                }
                $v['addtime'] = date('Y-m-d H:i:s',$member['addtime']);
                $v['id'] = $member['id'];
                $v['tel'] = $member['tel'];
                $v['username'] = $member['username'];
                $v['img'] = $member['img'];
                $v['sex'] = $member['sex'];
                $v['city'] = $member['city'];
                $v['bathday'] = $member['bathday'];
            }
        }catch (\Exception $e) {
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1,$e->getMessage());
        }

        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
}